function runAsyncTask(callback) {
    if (typeof queueMicrotask) {
      queueMicrotask(callback)
    } else if (typeof MutationObserver) {
      const mo = new MutationObserver(callback)
      const divNode = document.createElement('div')
      mo.observe(divNode, { childList: true })
      divNode.innerHTML = '我变了~'
    } else {
      setTimeout(callback, 0)
    }
  }

  function resolvePromise(x, p, resolve, reject) {
    if (x === p) {
      // console.log('x===p')
      const err = new TypeError('Uncaught (in promise) TypeError: Chaining cycle detected for promise #<Promise>')
      throw err
    }
    if (x instanceof myPromise) {
      x.then(res => resolve(res), err => reject(err))
    } else {
      resolve(x)
    }
  }

  // 声明变量存储三种状态
  const PENDING = 'pending'
  const FULFILLED = 'fulfilled'
  const REJECTED = 'rejected'
  // 定义myPromise类
  class myPromise {
    state = PENDING
    result = undefined
    //实例属性存异步回调
    #asyncArr = []
    // 构造函数：执行传入Promise实例的回调函数
    constructor(func) {
      //定义resolve
      const resolve = (result) => {
        // 如果是初始pending状态
        if (this.state === PENDING) {
          // console.log('resolve执行啦')
          this.state = FULFILLED        //状态改变为fulfilled
          this.result = result          //结果为传进来的参数
          // 遍历异步(状态未改变，仍为pending)任务数组
          this.#asyncArr.forEach(({ onFulfilled }) => {
            // 执行，此处为then(res=>{})
            onFulfilled(this.result)
          })
        }
      }
      // 定义reject,同上
      const reject = (result) => {
        // console.log('reject执行啦')
        if (this.state === PENDING) {
          this.state = REJECTED
          this.result = result
          this.#asyncArr.forEach(({ onRejected }) => {
            onRejected(this.result)
          })
        }
      }
      // 执行传入Promise实例的回调函数代码，new Promise((resolve,reject)=>{})
      // 这里resolve和reject都是回调函数，并且是异步执行的,但是func本身仍是同步执行的
      func(resolve, reject)
    }
    //实现then()方法：onFulfilled即then(res=>{},catch()=>{})
    then(onFulfilled, onRejected) {
      // console.log('onFulfilled:', onFulfilled)
      // console.log('onRejected:', onRejected)
      onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : x => x
      onRejected = typeof onRejected === 'function' ? onRejected : x => { throw x }

      // 返回新的Promise实例
      const p = new myPromise((resolve, reject) => {
        // 在这里直接封装为异步
        if (this.state === FULFILLED) {
          runAsyncTask(() => {
            // 获取返回值
            try {
              // 处理返回值
              const x = onFulfilled(this.result)
              resolvePromise(x, p, resolve, reject)
            } catch (error) {
              // 处理异常
              reject(error)
            }
          })
        } else if (this.state === REJECTED) {
          runAsyncTask(() => {
            try {
              const x = onRejected(this.result)
              resolvePromise(x, p, resolve, reject)
            } catch (error) {
              reject(error)
            }
          })
        } else if (this.state === PENDING) {      //状态未改变的放入asyncArr数组
          this.#asyncArr.push(
            {
              onFulfilled: () => {
                runAsyncTask(() => {
                  //1.捕获异常
                  try {
                    //2.拿到返回 
                    const x = onFulfilled(this.result)
                    //3.调取函数
                    resolvePromise(x, p, resolve, reject)
                  } catch (error) {
                    reject(error)
                  }
                })
              },
              onRejected: () => {
                runAsyncTask(() => {
                  //1.捕获异常
                  try {
                    //2.拿到返回 
                    const x = onRejected(this.result)
                    //3.调取函数
                    resolvePromise(x, p, resolve, reject)
                  } catch (error) {
                    reject(error)
                  }
                })
              }
            })
        }
      })
      return p
    }
    catch(onRejected) {
      return this.then(undefined, onRejected)
    }
    finally(onFinally) {
      return this.then(onFinally, onFinally)
    }
    // 静态方法resolve
    static resolve(value) {
      if (value instanceof myPromise) {
        return value
      }
      return new myPromise((resolve) => {
        resolve(value)
      })
    }
    static reject(value) {
      return new myPromise((undefined, reject) => {
        reject(value)
      })
    }
    static race(promiseArray) {
      return new myPromise((resolve, reject) => {
        if (!Array.isArray(promiseArray)) {
          return reject(new TypeError('undefined is not iterable (cannot read property Symbol(Symbol.iterator))'))
        }
        promiseArray.forEach(p => {
          myPromise.resolve(p).then(res => {
            resolve(res)
          }, err => {
            reject(err)
          })
        })
      })
    }
    static all(promiseArray) {
      return new myPromise((resolve, reject) => {
        if (!Array.isArray(promiseArray)) {
          return reject(new TypeError('undefined is not iterable (cannot read property Symbol(Symbol.iterator))'))
        }
        promiseArray.length === 0 && resolve(promiseArray)
        let result = []
        let count = 0
        promiseArray.forEach((p, index) => {
          myPromise.resolve(p).then(res => {
            result[index] = res
            count++
            count === promiseArray.length && resolve(result)
          }, err => {
            reject(err)
          })
        })
      })
    }
    static allSettled(promiseArray) {
      return new myPromise((resolve, reject) => {
        if (!Array.isArray(promiseArray)) {
          return reject(new TypeError('undefined is not iterable (cannot read property Symbol(Symbol.iterator))'))
        }
        promiseArray.length === 0 && resolve(promiseArray)
        let result = []
        let count = 0
        promiseArray.forEach((p, index) => {
          myPromise.resolve(p).then(
            res => {
              result[index] = { state: FULFILLED, value: res }
              count++
              count === promiseArray.length && resolve(result)
            },
            err => {
              result[index] = { state: REJECTED, reason: err }
              count++
              count === promiseArray.length && resolve(result)
            })
        })
      })
    }
    static any(promiseArray) {
      return new myPromise((resolve, reject) => {
        if (!Array.isArray(promiseArray)) {
          return reject(new TypeError('undefined is not iterable (cannot read property Symbol(Symbol.iterator))'))
        }
        promiseArray.length === 0 && reject(new AggregateError(promiseArray,'All promises were rejected'))
        const errors = []
        let count
        promiseArray.forEach((p, index) => {
          myPromise.resolve(p).then(
            res => {
              resolve(res)
            },
            err => {
              errors[index] = err
              count++
              count ===promiseArray.length && reject(new AggregateError(errors,'All promises were rejected'))
            })
        })
      })
    }
  }
  
  
  module.exports = {
    deferred() {
        const res = {}
        res.promise = new myPromise((resolve, reject) => {
            res.resolve = resolve
            res.reject = reject
        })
        return res
    }
  }